package com.braska.grave.netty.handler.executor;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author shenyuhang
 * @date 2020/3/30
 **/
public class NettyThreadFactory implements ThreadFactory {
    private AtomicInteger counter = new AtomicInteger(1);
    private AtomicInteger mThreadNum = new AtomicInteger(1);
    private String prefix;
    private boolean deamon;
    private final ThreadGroup threadGroup;

    public NettyThreadFactory(String prefix) {
        this(prefix, false);
    }

    public NettyThreadFactory(String prefix, boolean daemon) {
        this.prefix = String.format("%s-%s-", prefix, counter.getAndIncrement());
        this.deamon = daemon;
        SecurityManager security = System.getSecurityManager();
        threadGroup = (security == null) ? Thread.currentThread().getThreadGroup() : security.getThreadGroup();
    }

    @Override
    public Thread newThread(Runnable r) {
        String name = String.format("%s-%s", this.prefix, mThreadNum.getAndIncrement());
        Thread thread = new Thread(threadGroup, r, name);
        return thread;
    }
}
